package com.yj.springbootstudy.mulThread.demo;

import lombok.Data;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 模拟转账的案例
 */
public class TransferDemo {

    static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        Transfer a = new Transfer(1000);
        Transfer b = new Transfer(1000);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("总的金额："+(a.getMoney()+b.getMoney()));
    }

    public static int randomAmount() {

        return random.nextInt(100)+1;
    }
}

@Data
class Transfer {

    private int money;

    public Transfer(int money) {
        this.money = money;
    }

    public void transfer(Transfer target, int amount) {
        if (this.money >= amount) {
            this.setMoney(this.getMoney() - amount);
            target.setMoney(target.getMoney() + amount);
        }
    }


}
